﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using System.Collections.Generic;

namespace HealthCommunity.Controls
{
	public partial class UCSurveyEdit : System.Web.UI.UserControl
	{
		private ISurveyProvider _SurveyProvider;
		private List<DrugStore> lstDrugStore;

		private Survey _CurrentSurvey;

		private int _SurveyID;

		public int SurveyID
		{
			get
			{
				if(_SurveyID > 0)
				{
					return _SurveyID;
				}

				if(CommonHelper.QueryStringInt("surveyid") > 0)
				{
					_SurveyID = CommonHelper.QueryStringInt("surveyid");
				}
				else if(ViewState["surveyid"] != null)
				{
					_SurveyID = (int)ViewState["surveyid"];
				}

				return _SurveyID;
			}
			set
			{
				_SurveyID = value;
				ViewState["surveyid"] = _SurveyID;
			}
		}

		public int CurrentEditSurveyQuestionID
		{
			get
			{
				if(ViewState["CurrentEditSurveyQuestionID"] != null)
				{
					return (int)ViewState["CurrentEditSurveyQuestionID"];
				}
				else
				{
					return 0;
				}
			}
			set
			{
				ViewState["CurrentEditSurveyQuestionID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindDrugStore();
			}

			if(SurveyID > 0)
			{
				addedsurveyquestions.Visible = true;
				surveyquestionitem.Visible = true;

				if(!IsPostBack)
				{
					BindSurvey();
				}
			}
			else
			{
				addedsurveyquestions.Visible = false;
				surveyquestionitem.Visible = false;
			}
		}

		protected void ddlDrugStore_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindMember();
		}

		protected void btnRemove_Click(object sender, EventArgs e)
		{
			if(lstMemberSelected.SelectedItem != null)
			{
				lstMemberSelected.Items.Remove(lstMemberSelected.SelectedItem);
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			if(lstMember.SelectedItem != null)
			{
				var item = new System.Web.UI.WebControls.ListItem(lstMember.SelectedItem.Text, lstMember.SelectedItem.Value);

				if(!lstMemberSelected.Items.Contains(item))
				{
					lstMemberSelected.Items.Add(item);
				}
			}
		}

		protected void btnSaveSurvey_Click(object sender, EventArgs e)
		{
			if(_SurveyProvider == null)
			{
				_SurveyProvider = new SurveyProvider();
			}

			if(this.SurveyID <= 0)
			{
				var survey = new Survey() { SurveyDescription = txtSurveyDescription.Text.Trim(), SurveyTitle = txtSurveyTitle.Text.Trim() };

				var user = SiteContext.Current.CurrentUser;

				if(user != null)
				{
					survey.DrugStoreID = user.DrugStoreID;
				}

				survey.IsPublic = chbIsPublic.Checked ? 1 : 0;

				var msg = string.Empty;
				survey.SurveyDate = DateTime.Now;
				survey = _SurveyProvider.CreateSurvey(survey, out msg);

				if(survey != null)
				{
					this.SurveyID = survey.SurveyID;

					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_SurveyAndShareTo> lstNewSurveyAndShareTo = new List<RLT_SurveyAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltSurveyAndShareTo = new RLT_SurveyAndShareTo() { SurveyID = survey.SurveyID, ShareToDrugStoreID = id };
								lstNewSurveyAndShareTo.Add(rltSurveyAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltSurveyAndShareTo = new RLT_SurveyAndShareTo() { SurveyID = survey.SurveyID, ShareToMemberID = memberID };
								lstNewSurveyAndShareTo.Add(rltSurveyAndShareTo);
							}
						}

						if(lstNewSurveyAndShareTo.Count > 0)
						{
							_SurveyProvider.CreateSurveyAndShareTo(lstNewSurveyAndShareTo);
						}
					}

					addedsurveyquestions.Visible = true;
					surveyquestionitem.Visible = true;

					txtSurveyTitle.ReadOnly = true;
				}
				else
				{
					ltrMsg.Text = msg;
				}
			}
			else
			{
				var survey = _SurveyProvider.GetSurvey(this.SurveyID);
				survey.SurveyDescription = txtSurveyDescription.Text.Trim();
				survey.SurveyTitle = txtSurveyTitle.Text.Trim();
				survey.IsPublic = chbIsPublic.Checked ? 1 : 0;

				if(!_SurveyProvider.UpdateSurvey(survey))
				{
					ltrMsg.Text = "调查信息保存失败,检查标题是否已存在";
				}
				else
				{
					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_SurveyAndShareTo> lstNewSurveyAndShareTo = new List<RLT_SurveyAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltSurveyAndShareTo = new RLT_SurveyAndShareTo() { SurveyID = survey.SurveyID, ShareToDrugStoreID = id };
								lstNewSurveyAndShareTo.Add(rltSurveyAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltSurveyAndShareTo = new RLT_SurveyAndShareTo() { SurveyID = survey.SurveyID, ShareToMemberID = memberID };
								lstNewSurveyAndShareTo.Add(rltSurveyAndShareTo);
							}
						}

						if(lstNewSurveyAndShareTo.Count > 0)
						{
							_SurveyProvider.CreateSurveyAndShareTo(lstNewSurveyAndShareTo);
						}
					}
				}
			}
		}

		protected void btnAddSurveyQuestion_Click(object sender, EventArgs e)
		{
			var msg = string.Empty;
			if(SaveSurveyQuestion(out msg))
			{
				BindAddedSurveyQuestion();
				CleanQuestionItem();
				CurrentEditSurveyQuestionID = 0;
			}
			else
			{
				ltrMsg.Text = msg;
			}
		}

		private bool SaveSurveyQuestion(out string msg)
		{
			var surveyQuestion = new SurveyQuestion() { SurveyID = this.SurveyID, SurveyQuestionContent = txtSurveyQuestionContent.Text.Trim() };

			if(_SurveyProvider == null)
			{
				_SurveyProvider = new SurveyProvider();
			}

			if(rbtnlSurveyQuestionType.SelectedValue.Equals("3"))
			{
				surveyQuestion.SurveyQuestionType = (int)SurveyQuestionType.FillInBlank;

				msg = string.Empty;

				if(CurrentEditSurveyQuestionID <= 0)
				{
					if(_SurveyProvider.CreateSurveyQuestion(surveyQuestion, out msg) != null)
					{
						return true;
					}
					else
					{
						return false;
					}
				}
				else
				{
					if(_SurveyProvider.UpdateSurveyQuestion(surveyQuestion))
					{
						return true;
					}
					else
					{
						return false;
					}
				}
			}
			else
			{
				if(rbtnlSurveyQuestionType.SelectedValue.Equals("2"))
				{
					surveyQuestion.SurveyQuestionType = (int)SurveyQuestionType.MultiChoise;
				}
				else
				{
					surveyQuestion.SurveyQuestionType = (int)SurveyQuestionType.SingleChoise;
				}

				if(CurrentEditSurveyQuestionID > 0)
				{
					_SurveyProvider.DeleteSurveyQuestionItemByQuestion(surveyQuestion.SurveyQuestionID);
				}

				msg = string.Empty;
				surveyQuestion = _SurveyProvider.CreateSurveyQuestion(surveyQuestion, out msg);

				if(surveyQuestion != null)
				{
					var tagHasItems = false;

					SaveSurveyQuestionItems(surveyQuestion, ref tagHasItems);

					return true;
				}
				else
				{
					return false;
				}
			}
		}

		private void CleanQuestionItem()
		{
			//rbtnFillIn.Checked = false;
			//rbtnMultiChoice.Checked = false;
			//rbtnSingleChoice.Checked = false;
			rbtnlSurveyQuestionType.SelectedIndex = -1;
			txtSurveyQuestionContent.Text = string.Empty;
			CleanSurveyQuestionItems();
		}

		private void CleanSurveyQuestionItems()
		{
			txtSurveyQuestionItem1.Text = string.Empty;
			txtSurveyQuestionItem2.Text = string.Empty;
			txtSurveyQuestionItem3.Text = string.Empty;
			txtSurveyQuestionItem4.Text = string.Empty;
			txtSurveyQuestionItem5.Text = string.Empty;
			txtSurveyQuestionItem6.Text = string.Empty;
			txtSurveyQuestionItem7.Text = string.Empty;
			txtSurveyQuestionItem8.Text = string.Empty;
			txtSurveyQuestionItem9.Text = string.Empty;
			txtSurveyQuestionItem10.Text = string.Empty;
		}

		private void SaveSurveyQuestionItems(SurveyQuestion surveyQuestion, ref bool tagHasItems)
		{
			var msg = string.Empty;

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem1.Text.Trim()))
			{
				var surveyQuestionItem1 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "A", SurveyQuestionItemContent = txtSurveyQuestionItem1.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem1, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem2.Text.Trim()))
			{
				var surveyQuestionItem2 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "B", SurveyQuestionItemContent = txtSurveyQuestionItem2.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem2, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem3.Text.Trim()))
			{
				var surveyQuestionItem3 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "C", SurveyQuestionItemContent = txtSurveyQuestionItem3.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem3, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem4.Text.Trim()))
			{
				var surveyQuestionItem4 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "D", SurveyQuestionItemContent = txtSurveyQuestionItem4.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem4, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem5.Text.Trim()))
			{
				var surveyQuestionItem5 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "E", SurveyQuestionItemContent = txtSurveyQuestionItem5.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem5, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem6.Text.Trim()))
			{
				var surveyQuestionItem6 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "F", SurveyQuestionItemContent = txtSurveyQuestionItem6.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem6, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem7.Text.Trim()))
			{
				var surveyQuestionItem7 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "G", SurveyQuestionItemContent = txtSurveyQuestionItem7.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem7, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem8.Text.Trim()))
			{
				var surveyQuestionItem8 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "H", SurveyQuestionItemContent = txtSurveyQuestionItem8.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem8, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem9.Text.Trim()))
			{
				var surveyQuestionItem9 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "I", SurveyQuestionItemContent = txtSurveyQuestionItem9.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem9, out msg);
				tagHasItems = true;
			}

			if(!string.IsNullOrEmpty(txtSurveyQuestionItem10.Text.Trim()))
			{
				var surveyQuestionItem10 = new SurveyQuestionItem() { SurveyQuestionID = surveyQuestion.SurveyQuestionID, SurveyQuestionItemLabel = "J", SurveyQuestionItemContent = txtSurveyQuestionItem10.Text.Trim() };

				_SurveyProvider.CreateSurveyQuestionItem(surveyQuestionItem10, out msg);
				tagHasItems = true;
			}
		}

		private void BindAddedSurveyQuestion()
		{
			if(_SurveyProvider == null)
			{
				_SurveyProvider = new SurveyProvider();
			}

			rptSurveyQuestionsAdded.DataSource = _SurveyProvider.GetSurveyQuestionBySurvey(SurveyID);
			rptSurveyQuestionsAdded.DataBind();
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			//var msg = string.Empty;
			//if(SaveSurveyQuestion(out msg))
			//{
			this.Response.Redirect("SurveyList.aspx");
			//}
			//else
			//{
			//  ltrMsg.Text = msg;
			//}
		}

		protected void rptSurveyQuestionsAdded_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			//var dataSource = rptSurveyQuestionsAdded.DataSource as List<SurveyQuestion>;
			var id = int.Parse(e.CommandArgument.ToString());

			if(_SurveyProvider == null)
			{
				_SurveyProvider = new SurveyProvider();
			}

			var dataItem = _SurveyProvider.GetSurveyQuestion(id);

			if(e.CommandName.Equals("delete"))
			{
				var surveyQuestionID = dataItem.SurveyQuestionID;

				if(_SurveyProvider.DeleteSurveyQuestion(surveyQuestionID))
				{
					if(surveyQuestionID == CurrentEditSurveyQuestionID)
					{
						CurrentEditSurveyQuestionID = 0;
					}
					BindAddedSurveyQuestion();
				}
			}

			if(e.CommandName.Equals("edit"))
			{
				if(dataItem != null)
				{
					//rbtnSingleChoice.Checked = (dataItem.SurveyQuestionType == (int)SurveyQuestionType.SingleChoise);
					//rbtnMultiChoice.Checked = (dataItem.SurveyQuestionType == (int)SurveyQuestionType.MultiChoise);
					//rbtnFillIn.Checked = (dataItem.SurveyQuestionType == (int)SurveyQuestionType.FillInBlank);
					rbtnlSurveyQuestionType.SelectedIndex = dataItem.SurveyQuestionType.Value - 1;

					txtSurveyQuestionContent.Text = dataItem.SurveyQuestionContent;

					CurrentEditSurveyQuestionID = dataItem.SurveyQuestionID;

					if(dataItem.SurveyQuestionType != (int)SurveyQuestionType.FillInBlank)
					{
						if(_SurveyProvider == null)
						{
							_SurveyProvider = new SurveyProvider();
						}

						var surveyQuestionItems = _SurveyProvider.GetSurveyQuestionItemByQuestion(dataItem.SurveyQuestionID);

						if(surveyQuestionItems != null && surveyQuestionItems.Count > 0)
						{
							var orderedSurvQuestionItems = surveyQuestionItems.OrderBy(sqi => sqi.SurveyQuestionItemLabel).ToList();

							for(var i = 0; i < orderedSurvQuestionItems.Count; i++)
							{
								var txtSurveyQuestionItem = this.FindControl("txtSurveyQuestionItem" + (i + 1).ToString()) as TextBox;

								txtSurveyQuestionItem.Text = orderedSurvQuestionItems[i].SurveyQuestionItemContent;
							}

							if(orderedSurvQuestionItems.Count < 10)
							{
								for(var i = orderedSurvQuestionItems.Count + 1; i <= 10; i++)
								{
									var txtSurveyQuestionItem = this.FindControl("txtSurveyQuestionItem" + i.ToString()) as TextBox;
									txtSurveyQuestionItem.Text = string.Empty;
								}
							}
						}
					}
					else
					{
						CleanSurveyQuestionItems();
					}
				}
			}
		}

		private void BindSurvey()
		{
			if(SurveyID > 0)
			{
				if(_SurveyProvider == null)
				{
					_SurveyProvider = new SurveyProvider();
				}

				var theSurvey = _SurveyProvider.GetSurvey(SurveyID);

				if(theSurvey == null)
				{
					return;
				}

				txtSurveyTitle.Text = theSurvey.SurveyTitle;
				txtSurveyDescription.Text = theSurvey.SurveyDescription;

				if(theSurvey.IsPublic != 1)
				{
					var surveyAndShareTo = _SurveyProvider.GetSurveyAndShareToBySurvey(theSurvey.SurveyID);

					if(surveyAndShareTo != null && surveyAndShareTo.Count > 0)
					{
						var surveyAndShareToDrugStore = surveyAndShareTo.Where(vs => vs.ShareToDrugStoreID > 0);
						var surveyAndShareToMember = surveyAndShareTo.Where(vs => vs.ShareToMemberID > 0);

						if(surveyAndShareToDrugStore != null)
						{
							var lstSurveyShareToDrugStore = surveyAndShareToDrugStore.ToList();

							if(lstSurveyShareToDrugStore.Count > 0)
							{
								foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
								{
									var drugStoreID = int.Parse(item.Value);

									item.Selected = lstSurveyShareToDrugStore.Count(vs => vs.ShareToDrugStoreID == drugStoreID) > 0;
								}
							}
						}

						lstMemberSelected.Items.Clear();

						if(surveyAndShareToMember != null)
						{
							var lstVideoShareToMember = surveyAndShareToMember.ToList();

							if(lstVideoShareToMember.Count > 0)
							{
								var data = from vs in lstVideoShareToMember
													 select new { UserCName = vs.User.UserCName, ShareToMemberID = vs.ShareToMemberID };

								foreach(var dataItem in data)
								{
									var item = new System.Web.UI.WebControls.ListItem(dataItem.UserCName, dataItem.ShareToMemberID.ToString());

									//if (!lstMemberSelected.Items.Contains(item))
									//{
									lstMemberSelected.Items.Add(item);
									//}
								}
							}
						}
					}
				}

				// 已添加的题目
				var addedSurveyQuestions = _SurveyProvider.GetSurveyQuestionBySurvey(SurveyID);
				rptSurveyQuestionsAdded.DataSource = addedSurveyQuestions;
				rptSurveyQuestionsAdded.DataBind();
			}
		}

		private void BindDrugStore()
		{
			chblstDrugStore.Items.Clear();
			chblstDrugStore.DataSource = GetDrugStore();
			chblstDrugStore.DataBind();

			ddlDrugStore.Items.Clear();
			ddlDrugStore.DataSource = GetDrugStore();
			ddlDrugStore.DataBind();

			BindMember();
		}

		private void BindMember()
		{
			if(!string.IsNullOrWhiteSpace(ddlDrugStore.SelectedValue))
			{
				var selectedDrugStoreID = int.Parse(ddlDrugStore.SelectedValue);

				var userProvider = new UserProvider();

				lstMember.DataSource = userProvider.GetUserByDrugStore(selectedDrugStoreID, true);
				lstMember.DataBind();
			}
		}

		private List<DrugStore> GetDrugStore()
		{
			List<DrugStore> result;

			if(this.lstDrugStore != null)
			{
				result = lstDrugStore;
			}
			else
			{
				var drugStoreProvider = new DrugStoreProvider();

				lstDrugStore = drugStoreProvider.GetAllDrugStore();

				result = lstDrugStore;
			}

			return result;
		}
	}
}